# ---coding:utf8 ---
import datetime
import os.path
import subprocess

import requests
import win32gui
import win32con
import tkinter.filedialog as tkfd
import tkinter.simpledialog as tks
import sys


class Win32Tookits:
    def __init__(self):
        self.hwnd_titles = dict()

    @classmethod
    def get_hwnds(cls):
        hwnd_titles = list()

        def get_all_hwnd(hwnd, mouse):
            if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
                hwnd_titles.append(hwnd)

        win32gui.EnumWindows(get_all_hwnd, 0)
        return set(hwnd_titles)

    @classmethod
    def simple_top(cls, hwnd):
        win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0,
                              win32con.SWP_NOMOVE | win32con.SWP_NOACTIVATE | win32con.SWP_NOOWNERZORDER |
                              win32con.SWP_SHOWWINDOW | win32con.SWP_NOSIZE)


class ConfigToolkits:
    def __init__(self):
        pass

    @classmethod
    def checkconfig(cls, config: dict):
        """
        :param config: 检查内容是否完备。
        :return: config 返回完备的配置对象。
        """
        defaltdict = {
            'app': {
                "encoding": 'utf-8',
                'notebook': "None",
                "url": "https://gitee.com/ysu-xzh/notebook.git",
            },
            'filetree': {
                'openedfile': []
            },
            'load': {
                'ignoresuffix': ['.assets', ".git"]
            },
            "exec": {
                "open_dir": 'notepad'
            },
            "plugin": {}
        }

        defaltdict.update(config)
        defaltdict['app']['notebook'] = cls.askdirectory(defaltdict['app']['notebook'])
        config.update(defaltdict)
        return config

    @classmethod
    def askdirectory(self, directory, check=True):
        if directory == "None":
            if sys.platform == 'win32' and check:
                res = tkfd.askdirectory().replace('/', '\\')
            else:
                res = tkfd.askdirectory()
        else:
            res = directory
        return res



class FileToolkits:
    @classmethod
    def encode_name(cls, name):
        # 编码文件，用以支持自由明明特性。
        return ''.join([hex(ord(x)) for x in name])

    @classmethod
    def decode_name(cls, name):
        try:
            return ''.join([chr(eval('0x' + x)) for x in name[2:].split('0x')])
        except SyntaxError:
            return name

    @classmethod
    def get_suffix_from_filename(cls, filename):
        return '.' + filename.partition('.')[-1].lower()


class VersionToolkits:
    @classmethod
    def getlatestversion(cls):
        content = requests.get(
            "https://gitee.com/api/v5/repos/ysu-xzh/art-note/releases/latest", headers={'Connection': 'close'}
        ).json()
        tag = content['tag_name']
        title = content['name']
        body = content['body']
        url = content['assets'][0]['browser_download_url']
        return tag, title, body, url


class GitManager:
    def __init__(self, repo_path='.', repo_url=None):
        """
        初始化 GitManager 类，设置仓库路径。
        :param repo_path: 仓库路径，默认为当前目录
        :param origin: 远程仓库路径。
        """
        self.repo_path = repo_path
        self.repo_url = repo_url

    def run_command(self, command):
        """
        运行 Git 命令并返回输出。
        :param command: 要运行的 Git 命令
        :return: 命令的输出
        """
        try:
            result = subprocess.run(
                command,
                cwd=self.repo_path,
                shell=False,
                check=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                encoding="utf-8"
            )
            return result.stdout
        except subprocess.CalledProcessError as e:
            return f"Error: {e}"

    def is_inited(self):
        return os.path.isdir(os.path.join(self.repo_path, ".git"))

    def init(self):
        """
        初始化一个新的 Git 仓库。
        """
        res = self.run_command('git init')
        if self.repo_url is not None:
            res += "\n" + self.run_command("git remote add origin " + self.repo_url)
        return res

    def clone(self):
        """
        克隆一个远程仓库到本地。
        """
        assert self.repo_url is not None
        return self.run_command(f'git clone {self.repo_url}')

    def add(self, files='*'):
        """
        将文件添加到暂存区。

        :param files: 要添加的文件或目录，默认为当前目录下的所有文件
        """
        return self.run_command(f'git add {files}')

    def commit(self, message):
        """
        提交更改。

        :param message: 提交信息
        """
        return self.run_command(f'git commit -m "{message}"')

    def push(self, remote='origin', branch='master'):
        """
        推送更改到远程仓库。

        :param remote: 远程仓库名称，默认为 'origin'
        :param branch: 分支名称，默认为 'main'
        """
        return self.run_command(f'git push {remote} {branch}')

    def pull(self, remote='origin', branch='master'):
        """
        从远程仓库拉取更改。

        :param remote: 远程仓库名称，默认为 'origin'
        :param branch: 分支名称，默认为 'main'
        """
        return self.run_command(f'git pull {remote} {branch}')

    def status(self):
        """
        查看仓库状态。
        """
        return self.run_command('git status')

    def log(self):
        """
        查看提交日志。
        """
        return self.run_command('git log')

    def upload(self, verbose=False):
        if verbose:
            print(self.add())
            print(self.commit(datetime.datetime.now().strftime('%Y-%m-%d  %H:%M:%S')))
            print(self.push())
            res = ""
        else:
            res = "%s\n%s\n%s" % (self.add(),
                                  self.commit(datetime.datetime.now().strftime('%Y-%m-%d  %H:%M:%S')),
                                  self.push())
        return res

    def download(self, verbose=False):
        if verbose:
            if not self.is_inited():
                print(self.init())
            print(self.pull())
            return
        if not self.is_inited():
            res = self.init()
        else:
            res = ""
        res += "\n" + self.pull()
        return res


if __name__ == '__main__':
    print(VersionToolkits.getlatestversion())
